package com.bayes.teamshow.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bayes.teamshow.dao.ArticleSearch;
import com.bayes.teamshow.dao.UserManageRepository;
import com.bayes.teamshow.pojo.*;
import com.bayes.teamshow.service.ArticleSearchImp;
import com.bayes.teamshow.service.UserManagelmp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/blogManage")
public class testCon {
    //跳转到个人管理中心
    @RequestMapping("/personalInfo")
    public String getPersonalInfo(){
        return "personalInfo";
    }

    //跳转到博客管理中心
    @RequestMapping("/blogManage")
    public String getBlogManage(){
        return "blogManage";
    }

    //跳转到用户管理中心
    @RequestMapping("/userManage")
    public String getUserManage(){
        return "userManage";
    }

    //测试显示博客
    @Autowired
    ArticleSearchImp articleSearchImp;
    @RequestMapping("/testBlog")
    @ResponseBody
    public Object testBlog(){
        JSONObject myjson=new JSONObject();
        JSONArray myjsonarr=new JSONArray();
//        myjsonarr.add(new User(1,"asd","sdfas"));
//        myjsonarr.add(new User(2,"asd1","sdfas2"));
//        myjsonarr.add(new User(3,"aasdsf1","sdsdfas2"));
//        myjsonarr.add(new User(4,"asdfsd1","sdsdffas2"));
//        myjsonarr.add(new User(5,"assdfd1","sdfsdfas2"));
//        myjsonarr.add(new User(6,"assdd1","sdsdfas2"));
        myjson.put("data", articleSearchImp.findAllArticals());
//        myjson.put("that","123");
        myjson.put("pageNums",articleSearchImp.BlogCounts(10));
        return myjson;
    }

    //测试分页
    @RequestMapping("/testPage")
    @ResponseBody
    public Object testMyPage(@RequestParam("pagesize") String pagesize,@RequestParam("current") String current,
                             @RequestParam("blogName") String blogName,@RequestParam("blogAuthor") String blogAuthor,
                             @RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime){
        JSONObject myjson=new JSONObject();

        int pageSize=0;
        int currentPage=0;
        if(pagesize==null){
            pageSize= 5;
        }
        if(current==null){
            currentPage = 0;
        }
        Sort sort = new Sort(Sort.Direction.DESC,"Id");
        Pageable pageable = new PageRequest(currentPage,pageSize,sort);

        //无条件分页查询
        if(blogName==null&&blogAuthor==null&&startTime==null&&endTime==null){
            Page<Article> page = articleSearch.findAll(pageable);
            myjson.put("totalPageNum",page.getTotalPages());
            myjson.put("content",page.getContent());
            return myjson;
        }

        //已有博客文章名
       if(blogName!=null) {
           Page<Article> pageInfo = articleSearch.findAll(new Specification<Article>() {
               @Override
               public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                   Predicate predicate = criteriaBuilder.equal(root.get("title").as(String.class), blogName);
                   return criteriaBuilder.and(predicate);
               }
           }, pageable);

          myjson.put("content",pageInfo.getContent()) ;

       }



        return myjson;
    }

    //测试json
    @RequestMapping("/testJson")
    @ResponseBody
    public Object testMyJson(@RequestParam("username") String username,@RequestParam("userpwd") String userpwd){
        JSONObject myjson=new JSONObject();
        myjson.put("username",username);
        myjson.put("password",userpwd);
        System.out.println(myjson);
        return myjson;
    }



    //总分页查询
    @Autowired
    ArticleSearch articleSearch;
    @RequestMapping("/allBlog")
    @ResponseBody
    public Object allBlog(HttpServletRequest httpServletRequest){
        JSONObject myjson=new JSONObject();
        int current=1;int size=5;

        if(httpServletRequest.getParameter("current")!=null) {
            current = Integer.parseInt(httpServletRequest.getParameter("current")) - 1;
        }
        if(httpServletRequest.getParameter("pagesize")!=null) {
            size = Integer.parseInt(httpServletRequest.getParameter("pagesize"));
        }
        //无条件分页查询
        Sort sort = new Sort(Sort.Direction.DESC,"Id");
        Pageable pageable = new PageRequest(current,size,sort);
//        Page<Article> page = articleSearch.findAll(pageable);
//        myjson.put("data",page.getTotalPages());
//        myjson.put("content",page.getContent());


        String blogName = httpServletRequest.getParameter("blogName");//文章标题
        String blogAuthor = httpServletRequest.getParameter("blogAuthor");//作者
        String startTime = httpServletRequest.getParameter("startTime");//查询开始时间
        String endTime = httpServletRequest.getParameter("endTime");//查询结束时间

        //无条件查询
        if(blogName==""&&blogAuthor==""&&(startTime==""||endTime=="")){
           Page<Article> page = articleSearch.findAll(pageable);
            myjson.put("conten",page.getContent());
            myjson.put("allpage",page.getTotalPages());
            return myjson;
        }

        //有条件查询
           Page<Article> pageInfo = articleSearch.findAll(new Specification<Article>() {
               @Override
               public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                   Predicate predicateTitle = null;
                   Predicate predicateAuthor = null;
                   Predicate predicateStartTime=null;
                   Predicate predicateEndTime = null;

                   List<Predicate> predicatesList = new ArrayList<Predicate>();

                    //已有博客文章名
                   if(blogName!=""){
                       predicateTitle = criteriaBuilder.like(root.get("title").as(String.class), "%"+blogName+"%");
                       predicatesList.add(predicateTitle);
                   }
                   //已有博客作者
                   if(blogAuthor!=""){
                       predicateAuthor = criteriaBuilder.equal(root.get("createname").as(String.class), blogAuthor);
                       predicatesList.add(predicateAuthor);
                   }
                   //已有开始时间
                   if(startTime!=""){
                       Date starttime = articleSearchImp.timeStripToDate(startTime);
                       predicateStartTime = criteriaBuilder.greaterThanOrEqualTo(root.get("createdDate").as(Date.class), starttime);
                       predicatesList.add(predicateStartTime);
                   }
                   //已有结束时间
                   if(endTime!=""){
                       Date endtime = articleSearchImp.timeStripToDate(endTime);
                       predicateEndTime = criteriaBuilder.lessThanOrEqualTo(root.get("createdDate").as(Date.class), endtime);
                       predicatesList.add(predicateEndTime);
                   }

                    Predicate[] pArray = new Predicate[predicatesList.size()];
                   return criteriaBuilder.and(predicatesList.toArray(pArray));
               }
           },pageable);

           myjson.put("conten",pageInfo.getContent());
           myjson.put("allpage",pageInfo.getTotalPages());

        return myjson;
    }



    //删除文章
    @RequestMapping("/deleteBlog")
    @ResponseBody
    public boolean deleteBlog(HttpServletRequest httpServletRequest){
        int blogId = Integer.parseInt(httpServletRequest.getParameter("id"));
        articleSearchImp.deleteBlog(blogId);
        return true;
    }


    //删除用户
    @Autowired
    UserManagelmp userManagelmp;
    @RequestMapping("/deleteUser")
    @ResponseBody
    public boolean deleteUser(HttpServletRequest httpServletRequest){
        long userId = Long.parseLong(httpServletRequest.getParameter("uid"));
        userManagelmp.deleteUser(userId);
        return true;
    }



    //用户管理分页
    @RequestMapping("/allUsers")
    @ResponseBody
    public Object allUsers(HttpServletRequest httpServletRequest) {
        JSONObject myjson = new JSONObject();
        int current = 1;
        int size = 10;

        if (httpServletRequest.getParameter("current") != "") {
            current = Integer.parseInt(httpServletRequest.getParameter("current")) - 1;
        }
        if (httpServletRequest.getParameter("pagesize") != "") {
            size = Integer.parseInt(httpServletRequest.getParameter("pagesize"));
        }
        //无条件分页查询
        Sort sort = new Sort(Sort.Direction.DESC, "Id");
        Pageable pageable = new PageRequest(current, size, sort);
//        Page<Article> page = articleSearch.findAll(pageable);
//        myjson.put("data",page.getTotalPages());
//        myjson.put("content",page.getContent());

        ////无条件查询
        Page<UserBackground> page = userManagelmp.findAll(pageable);
        myjson.put("conten", page.getContent());
        myjson.put("allpage", page.getTotalPages());
        return myjson;
    }


}
